package giermala.dominik.fotka.controller;

import giermala.dominik.fotka.domain.User;
import giermala.dominik.fotka.service.CustomUserDetailsService;

import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class UserController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	CustomUserDetailsService customUserDetailsService;
	
	@RequestMapping(value = "/create_user.html", method = RequestMethod.GET)
	public String getUserForm(Locale locale, Model model) {
		logger.info("Get User Form");

		return "create_user";
	}

	@RequestMapping(value = "/create_user.html", method = RequestMethod.POST)
	public String createUser(@Validated @ModelAttribute User user, BindingResult result) {

		logger.info("New User Creation");
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				logger.info("Error: " + error.getCode() + " - " + error.getDefaultMessage());
			}
			return "create_user";
		}
		customUserDetailsService.saveUser(user);

		logger.info("User: " + user.getUsername() + ", password: " + user.getPassword());
		
		return "redirect:/login.html";
	}
}
